using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Framework.Singleton
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T instance = null;

        public static bool IsEnable => instance != null;
        
        public static T Instance
        {
            get
            {
                //不保证线程安全
                if (instance == null)
                {
                    instance = GameObject.FindObjectOfType<T>();
                    if (instance == null)
                    {
                        GameObject container = new GameObject(typeof(T).Name);
                        instance = container.AddComponent<T>();
                        
                        GameObject.DontDestroyOnLoad(container);
                    }
                }
                return instance;
            }
        }
    }
}
